<?php

namespace App\Http\Controllers;

use App\Models\Comments;
use App\Models\Videos;
use Carbon\Carbon;
use Illuminate\Http\Request;

/**
 * 评论相关
 * Class FollowController
 * @package App\Http\Controllers
 */
class CommentController extends Controller{

    /**
     * 评论列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request){
        try {
            $id = (int)$request->get('id');
            if(empty($id)){
                return $this->returnJson(1,'参数错误');
            }
            $lists = Comments::select('id', 'video_id', 'content', 'userid', 'replay_id','praise','created_at')
                ->where('video_id', $id)
                ->with(['user' => function ($query) {
                    $query->select('id', 'username', 'avatar')->get();
                }])
                ->with(['replay' => function ($query) {
                    $query->select('id', 'username')->get();
                }])
                ->orderBy('created_at', 'DESC')
                ->paginate(8);
            return $this->returnJson(0, '', $lists);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }

    /**
     * 评论视频
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function replay(Request $request){
//        try {
            //推送模板消息
            $data = $request->all();
            if(empty($data['video_id'])){
                return $this->returnJson(1,'参数错误');
            }
            $data['userid'] = auth()->guard('api')->id();
            $data['created_at'] = Carbon::now();
            $data['add_at'] = Carbon::now();
            //判断过快
            $praise = Comments::where('video_id',$data['video_id'])
                ->where('userid',$data['userid'])
                ->orderBy('created_at','DESC')
                ->first();
            if($praise && (time()-$praise['add_at']->timestamp < 5)){
                return $this->returnJson(1,'你的操作太频繁');
            }
            Comments::create($data);
            //更新统计数
            Videos::where('id',$data['video_id'])->increment('comment_count');
            return $this->returnJson(0);
//        } catch (\Exception $e) {
//            return $this->returnJson(1, '网络超时，请刷新再试');
//        }
    }

}
